package com.goblin.model.uaa.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import com.goblin.common.response.Code;
import com.goblin.common.response.Message;
import com.goblin.common.response.PageHelper;
import com.goblin.common.response.Paged;
import com.goblin.common.response.Response;
import com.goblin.common.util.MessageDigestUtil;
import com.goblin.model.uaa.po.Menu;
import com.goblin.model.uaa.po.Priv;
import com.goblin.model.uaa.po.User;
import com.goblin.model.uaa.repository.UserRepository;
import com.goblin.security.AuthorityStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserRepository userRepository;

	@Override
	public Paged<User> paged(PageHelper pageable) {
		return this.userRepository.paged(pageable);

	}

	@Override
	public Response login(User user) {

		Optional<User> optional = this.userRepository
				.findUserByMobileOrNickNameOrEmail(user.getNickName(), user.getNickName(),
						user.getNickName());

		if (optional.isPresent()) {
			String password = MessageDigestUtil.base64AndMD5(user.getPassword());
			if (optional.get().getPassword().equals(password)) {

				//生成登录信息
				List loginInfo = new ArrayList();

				//登录时间
				loginInfo.add(System.currentTimeMillis());

				//登录用户信息
				User u = optional.get();
				u.setPassword(null);
				loginInfo.add(u);

				//菜单列表
				List<Menu> menus = new ArrayList<>();
				optional.get().getRoles().forEach((e) -> {
					menus.addAll(e.getMenus());
				});

				List<Menu> root = new ArrayList<>();
				for (Menu m : menus) {
					if (m.getParentId() == 0) {
						root.add(m);
					}
				}

				//确定菜单树
				menuTree(root, menus);
				loginInfo.add(root);

				//确定权限列表
				List<Priv> privs = new ArrayList<>();
				optional.get().getRoles().forEach((e) -> {
					e.getPrivs().forEach((v) -> {
						if (v.getUrl().equalsIgnoreCase("/")) {
							return;
						}
						if (!privs.contains(v)) {
							privs.add(v);
						}
					});
				});
				loginInfo.add(privs);

				u.setRoles(null);

				String token = UUID.randomUUID().toString();

				AuthorityStore.saveAuth(token, loginInfo);

				loginInfo.add(token);

				return Response.success(loginInfo);
			}
		}

		return Response.failure(Code.BAD_REQUEST, Message.ACCOUNT_PASSWORD_ERROR);
	}

	@Override
	public User save(User user) {
		return this.userRepository.save(user);
	}

	@Override
	public Optional<User> findUserByNickName(String nickName) {
		return this.userRepository.findUserByNickName(nickName);
	}

	private void menuTree(List<Menu> root, List<Menu> menus) {
		int i = 0;
		for (Menu m : root) {
			if (i == root.size() - 1) {
				return;
			}
			if (!menus.contains(m)) {
				root.remove(m);
			}
			else {
				menuTree(m.getChildren(), menus);
			}

			i++;

		}
	}
}
